//
// (C) Copyright 2009 Irantha Suwandarathna (irantha@gmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


using System;
using System.IO;
using System.Text;
using EffiProzDB.Lib;
using EffiProzDB.Persist;
using EffiProzDB.DataTypes;

namespace EffiProzDB.RowIO
{

    /**
     *  Class for writing the data for a database row _in text table format.
     *
     * @author sqlbob@users (RMP)
     * @version 1.8.0
     * @since 1.7.0
     */
    public class RowOutputText : RowOutputBase
    {

        protected string fieldSep;
        protected string varSep;
        protected string longvarSep;
        private bool fieldSepEnd;
        private bool varSepEnd;
        private bool longvarSepEnd;
        private string nextSep = "";
        private bool nextSepEnd;
        protected bool allQuoted;
        private string encoding;

        public RowOutputText(string fieldSep, string varSep, string longvarSep,
                             bool allQuoted, string encoding)
            : base()
        {


            initTextDatabaseRowOutput(fieldSep, varSep, longvarSep, allQuoted,
                                      encoding);
        }

        private void initTextDatabaseRowOutput(string fieldSep, string varSep,
                                               string longvarSep,
                                               bool allQuoted,
                                               string encoding)
        {

            //-- Newline indicates that field should match to end of line.
            if (fieldSep.EndsWith("\n"))
            {
                fieldSepEnd = true;
                fieldSep = fieldSep.Substring(0, fieldSep.Length - 1);
            }

            if (varSep.EndsWith("\n"))
            {
                varSepEnd = true;
                varSep = varSep.Substring(0, varSep.Length - 1);
            }

            if (longvarSep.EndsWith("\n"))
            {
                longvarSepEnd = true;
                longvarSep = longvarSep.Substring(0, longvarSep.Length - 1);
            }

            this.fieldSep = fieldSep;
            this.varSep = varSep;
            this.longvarSep = longvarSep;
            this.allQuoted = allQuoted;
            this.encoding = encoding;
        }

        public override void writeEnd()
        {

            // terminate at the end of row
            if (nextSepEnd)
            {
                writeBytes(nextSep);
            }

            writeBytes(TextCache.NL);
        }

        public override void writeSize(int size)
        {

            // initialise at the start of row
            nextSep = "";
            nextSepEnd = false;
        }

        public override void writeType(int type)
        {

            //--do Nothing
        }

        public override void writeString(string s)
        {

            s = checkConvertString(s, fieldSep);

            // error
            if (s == null)
            {
                return;
            }

            // writeBytes(s);
            byte[] bytes = getBytes(s);

            write(bytes, 0, bytes.Length);

            nextSep = fieldSep;
            nextSepEnd = fieldSepEnd;
        }

        protected void writeVarString(string s)
        {

            s = checkConvertString(s, varSep);

            if (s == null)
            {
                return;
            }

            // writeBytes(s);
            byte[] bytes = getBytes(s);

            write(bytes, 0, bytes.Length);

            nextSep = varSep;
            nextSepEnd = varSepEnd;
        }

        protected void writeLongVarString(string s)
        {

            s = checkConvertString(s, longvarSep);

            if (s == null)
            {
                return;
            }

            // writeBytes(s);
            byte[] bytes = getBytes(s);

            write(bytes, 0, bytes.Length);

            nextSep = longvarSep;
            nextSepEnd = longvarSepEnd;
        }

        protected virtual string checkConvertString(string s, string sep)
        {

            if (s.IndexOf('\n') != -1 || s.IndexOf('\r') != -1)
            {
                throw new ArgumentException(
                    Trace.getMessage(Trace.TEXT_STRING_HAS_NEWLINE));
            }
            else if (s.IndexOf(sep) != -1)
            {
                return null;
            }

            return s;
        }

        private byte[] getBytes(string s)
        {

            byte[] bytes = null;

            try
            {
                Encoding encordingo = Encoding.GetEncoding(encoding);
                bytes = encordingo.GetBytes(s);
            }
            catch (Exception)
            {
                bytes = Encoding.Default.GetBytes(s);
            }

            return bytes;
        }

        protected void writeByteArray(byte[] b)
        {

            ensureRoom(b.Length * 2);
            StringConverter.writeHex(this.getBuffer(), count, b);

            count += b.Length * 2;
        }

        public override void writeShortData(short i)
        {
            writeIntData(i);
        }

        public override void writeIntData(int i)
        {

            writeBytes(i.ToString());

            nextSep = fieldSep;
            nextSepEnd = fieldSepEnd;
        }

        public override void writeIntData(int i, int position)
        {
            throw Trace.runtimeError(Trace.UNSUPPORTED_INTERNAL_OPERATION,
                                     "RowInputText");
        }

        public override void writeLongData(long i)
        {
            throw Trace.runtimeError(Trace.UNSUPPORTED_INTERNAL_OPERATION,
                                     "RowInputText");
        }

        // fredt@users - comment - methods used for writing each SQL type
        protected override void writeFieldType(int type)
        {

            writeBytes(nextSep);

            switch (type)
            {

                case Types.VARCHAR:
                case Types.VARCHAR_IGNORECASE:
                    nextSep = varSep;
                    nextSepEnd = varSepEnd;
                    break;

                case Types.LONGVARCHAR:
                    nextSep = longvarSep;
                    nextSepEnd = longvarSepEnd;
                    break;

                default:
                    nextSep = fieldSep;
                    nextSepEnd = fieldSepEnd;
                    break;
            }
        }

        protected override void writeNull(int type)
        {
            writeFieldType(type);
        }

        protected override void writeChar(string s, int t)
        {

            switch (t)
            {

                case Types.CHAR:
                    writeString(s);

                    return;

                case Types.VARCHAR:
                case Types.VARCHAR_IGNORECASE:
                    writeVarString(s);

                    return;

                case Types.LONGVARCHAR:
                default:
                    writeLongVarString(s);

                    return;
            }
        }

        protected override void writeSmallint(short o)
        {
            writeString(o.ToString());
        }

        protected override void writeInteger(int o)
        {
            writeString(o.ToString());
        }

        protected override void writeBigint(long o)
        {
            writeString(o.ToString());
        }

        protected override void writeReal(Double o, int type)
        {
            writeString(o.ToString());
        }

        protected override void writeDecimal(Decimal o)
        {
            writeString(o.ToString());
        }

        protected override void writeBit(bool o)
        {
            writeString(o.ToString());
        }

        protected override void writeDate(DateTime o)
        {
            writeString(o.ToString());
        }

        protected override void writeTime(DateTime o)
        {
            writeString(o.ToString());
        }

        protected override void writeTimestamp(DateTime o)
        {
            writeString(o.ToString());
        }

        protected override void writeOther(DotNetObject o)
        {

            byte[] ba = o.getBytes();

            writeByteArray(ba);
        }

        protected override void writeBinary(Binary o, int t)
        {
            writeByteArray(o.getBytes());
        }

        public override int getSize(CachedRow r)
        {

            reset();

            try
            {
                writeSize(0);
                writeData(r.getData(), r.getTable());
                writeEnd();
            }
            catch (Exception )
            {
                reset();

                //            throw (Trace.error(Trace.FILE_IO_ERROR, e.ToString()));
            }

            int rowsize = size();

            reset();

            return rowsize;
        }
    }
}
